05. Struct or Variable?
It is time for an exercise called “Struct or Variable?” We'll provide a list of names, then you must decide if you think each item would be better represented as a simple, primitive variable, or a struct.
QUESTION:
Here are the names. What do you think? Struct or variable?
librarysubTitlenumberOfPagesbookweightfictional
ANSWER:
Here’s what we answered:
library- For library, a bunch of values come to mind. A library can have a name, an address, hours of operation, etc. So given this name, we'd go with a struct.
subTitle- Subtitles are usually just simple strings. Therefore, it should probably be a
Stringvariable.
- Subtitles are usually just simple strings. Therefore, it should probably be a
numberOfPages- The number of pages is a number. So an
Intvariable would work fine.
- The number of pages is a number. So an
book- This could swing either way. On one hand, someone might just use the name
bookfor aStringvariable that contains a book’s title. But if that were the case, then we might want to use a more descriptive name likebookTitle. So in this case, let’s go with struct. ABookstruct could contain information like a title, subtitle, number of pages, and so on.
- This could swing either way. On one hand, someone might just use the name
weight- Weight is usually a single measurement. We'd go with a variable — probably of
Doubletype.
- Weight is usually a single measurement. We'd go with a variable — probably of
fictional- This name is indicative of a
Boolvariable. A book is either fictional or it’s not—trueorfalse.
- This name is indicative of a
Valid or Invalid?
For this exercise, let’s take a look at this snippet of code. Some of the lines in this snippet contain errors, but we've removed them to see if you can identify them.
Which lines in this example contain an error?
QUESTION:
It is your job to indicate which lines in this snippet cause the Swift compiler to complain. Try attempting this without copying the code into a Playground.
ANSWER:
If you said there were errors in braves.name, freddie.hometown, and myFavoriteTeam (lines 17, 19, and 23)—you're right! Read on for more details.